
// Show the content of a message
// ==========================================

function showMessageContent (docID) {
	callJSON('/ui/content/mail/' + docID,
		 renderMessageContent, docID);	
}

// Show content list in place
// ==========================================

function doShowContentInPlace (threadID) {
	var widget = $('item.' + threadID + '.content');
	var data = gData.currThreads[threadID];
	
	widget.innerHTML = '';

	for (var i in data.docList) {
		var content = Widget('div',
				     'content.' + data.docList[i],
				     'mailContent')
		widget.appendChild(content);
		showMessageContent (data.docList[i]);
	}
	widget.style.display = 'block';
}

function showContentInPlace (threadID) {
	callJSON('/ui/list/threadUnread/' + threadID,
		 function (retData) {
			 // Set the data
			 gData.currThreads[threadID].docList = retData[1];
			 // Show it
			 doShowContentInPlace(threadID);
			 setThreadAsRead(threadID);
		 }
		);	
}

function jumptoThreadContent (threadID) {
	window.open('/mail.html#' + threadID, '_blank');
}

// To control the showing
function showThread (servReturn, threadID) {
	var isStar = servReturn[0];
	var docList = servReturn[1];

	// Make a fake gData
	var data = {};
	data.isStar = isStar;
	data.docList = docList;
	data.numUnread = 0;

	gData.currThreads = {}
	gData.currThreads[threadID] = data;

	// Now create the framework;
	var widget = $('threadMails');
	var titleWidget = Widget ('div', 'threadTitle', 'wholeThreadTitle');
	widget.appendChild(titleWidget);

	for (var i in docList) {
		var content = Widget('div',
				     'content.' + docList[i],
				     'mailContent');
		widget.appendChild(content);
		var docID = docList[i];		
		if (i == 0) {
			callJSON('/ui/content/mail/' + docID,
				 function (retData, docID) {
					 renderMessageContent(retData, docID);
					 setWholeThreadTitle(threadID,
							     retData);
					 renderMessageTitle(threadID);
				 },
				 docID);
		} else {
			showMessageContent(docID);
		}
	}
	commitThreadAsRead(threadID);	
}

function setWholeThreadTitle(threadID, retData) {
	// Provide data for render
	gData.currThreads[threadID].subject = retData[0].subject;	
}

function showMail () {
	threadID = parseInt(getResource());
	callJSON ('/ui/list/thread/' + threadID,
		  showThread, threadID);
}


function selectThread (threadID) {
	if (threadID == gData.openThread) {
		closeThread(threadID);
		return;
	}
	
	var data = gData.currThreads[threadID];

	if (data.numUnread == 0) {
		jumptoThreadContent(threadID)
		return;
	}

	// close previous open thread
	if (gData.openThread != -1)
		closeThread(gData.openThread);

	// Now we will show the content	
	gData.openThread = threadID;
	showContentInPlace(threadID);
}

function closeThread (threadID) {
	if (threadID == -1) return false;
	
	// Hide the widget
	var widget = $('item.' + threadID + '.content');
	widget.innerHTML = '';
	widget.style.display = 'none';

	gData.openThread = -1;
	
}

